<?php

namespace App\Http\Logic\Admin;

use App;
use App\Common\Status;
use App\Models\RecruitMenu;
use Illuminate\Support\Facades\DB;

class MenusLogic
{
    /**
     * @param $adminId
     * @return array
     */
    public static function getMenus($adminId)
    {
        $where['status'] = Status::REGULAR;

        # 获取用户角色
        if(empty($adminId->role)) {
            return ['status'=>Status::ERROR,'msg'=>"用户角色不存在"];
        }
        if($adminId->role->menus->isEmpty()) {
            return ['status'=>Status::ERROR,'msg'=>"用户角色目录不存在"];
        }

        # 获取角色菜单id
        $menusIds = $adminId->role->menus->pluck('id');
        $menus = RecruitMenu::where($where)->whereIn('id',$menusIds)->get();

        if($menus->isNotEmpty()) {
            $menus = $menus->toArray();
        }
        $vueMenus = $actions = [];
        foreach ($menus as $menu) {
            if ($menu['type'] === 3) {
                $actions[] = $menu['action'];
            } else {
                $vueMenus[] = $menu;
            }
        }

        return [
            'menus' => self::getMenuTree($vueMenus),
            'actions' => $actions,
        ];
    }


    public static function getMenuTree(array $menus)
    {
        $data = [];
        foreach ($menus as $menu) {
            if ($menu['parent_id'] === 0) {
                $data[] = self::getChildren($menus, $menu);
            }
        }

        return $data;
    }

    public static function getChildren($menus, $menu)
    {
        $c = [];
        foreach ($menus as $children) {
            if ($menu['id'] === $children['parent_id']) {
                $c[] = self::getChildren($menus, $children);
            }
        }
        $menu['children'] = $c;
        return $menu;
    }

}
